/*
 * @Description:
 * @Author: 阳婷
 * @Date: 2019-07-30 10:21:49
 * @LastEditTime: 2024-04-07 10:23:32
 * @LastEditors: 阳婷
 */
/**
 * 登录专用ajax
 * @method Ajax 方法
 * @param TYPE  请求方式
 * @param URL   请求url
 * @param DATA  请求参数
 * @param FN    返回方法
 */
import { ElMessage } from "element-plus";
import axios from "axios";
// import Qs from "qs";
import router from "@/router";
import NProgress from "nprogress"; // Progress 进度条
import "nprogress/nprogress.css"; // Progress 进度条样式

export default function $ajax(TYPE, URL, DATA, FN) {
  NProgress.start();
  let pub =
    process.env.NODE_ENV === "production"
      ? process.env.VUE_APP_BASE_URL
      : "http://192.168.11.120:8087";
  let url = pub + URL;
  if (TYPE.toLowerCase() == "post") {
    PostAjax(url, DATA, FN);
  } else if (TYPE.toLowerCase() == "get") {
    GetAjax(url, DATA, FN);
  }
}
/*
 *  get请求 不带token
 *  URL:请求地址
 *  DATA:参数
 *  FN:回调函数
 * */
function GetAjax(URL, DATA, FN) {
  axios
    .get(URL, {
      params: DATA,
      paramsSerializer: (params) => {
        return JSON.stringify(params, { arrayFormat: "indices" });
      },
    })
    .then((response) => {
      Judge(response.data, FN);
    });
}
/*
 *  post请求
 *  URL:请求地址
 *  DATA:参数
 *  FN:回调函数
 * */
function PostAjax(URL, DATA, FN) {
  axios
    .post(URL, JSON.stringify(DATA), {
      headers: {
        // Authorization: "Bearer ",
        "Content-Type": "application/json",
      },
    })
    .then((response) => {
      Judge(response.data, FN);
    });
}

/*
 *  body:后台返回值
 *  FN:回调函数
 *  code:状态值判断
 * */
function Judge(body, FN) {
  NProgress.done();
  if (body.code == 200) {
    FN(body);
  } else if (body.code == 401) {
    if (router.currentRoute.value.fullPath != "/login") {
      ElMessage({
        showClose: true,
        message: "登录超时，请重新登录",
        type: "error",
      });
      router.push({
        path: "/login",
      });
      setTimeout(() => {
        location.reload(); // 为了重新实例化vue-router对象 避免bug
      }, 400);
    }
    return;
  } else if (body.code == -1) {
    // FN(body);
    ElMessage({
      showClose: true,
      message: body.msg,
      type: "warning",
    });
  } else {
    ElMessage({
      showClose: true,
      message: body.msg,
      type: "warning",
    });
  }
}
